const jwt = require("jsonwebtoken");
const User = require("../models/User");
const { secret } = require("../config/config");

exports.register = async function (req, res, next) {
  console.log(req.body);
  try {
    const { username, email, password } = req.body;
    const existingEmail = await User.findOne({ where: { email } });
    const existingUser = await User.findOne({ where: { username } });

    // 验证邮箱是否已被注册
    if (existingUser) {
      return res.status(400).json({ message: "该用户名已被注册" });
    }
    // 验证邮箱是否已被注册
    if (existingEmail) {
      return res.status(400).json({ message: "该邮箱已被注册" });
    }

    // 创建新用户
    const newUser = new User({ username, email, password });

    await newUser.save();

    res.status(201).json({ message: "用户创建成功" });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "服务器错误" });
  }
};

exports.login = async function (req, res) {
  console.log("*******", req.body);
  try {
    const { email, password } = req.body;
    const user = await User.findOne({ where: { email } });

    // 验证用户是否存在
    if (!user) {
      return res.status(401).json({ message: "邮箱不存在" });
    }

    // 验证用户密码
    const isValidPassword = await user.isValidPassword(password);
    if (!isValidPassword) {
      return res.status(401).json({ message: "密码错误" });
    }

    // 生成 JWT
    const token = jwt.sign({ id: user.id }, secret, {
      expiresIn: "30d",
    });

    res.status(200).json({ token, ...user.dataValues, password: undefined });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "服务器错误" });
  }
};

exports.getUserInfo = async (req, res) => {
  try {
    const token = req.headers.token;
    console.log("***************", token);

    jwt.verify(token, secret, async (err, decoded) => {
      if (err) {
        // token 验证失败
        return res.status(401).json({ error: "用户未登录" });
      } else {
        // token 验证成功，解析出的数据存储在 decoded 中
        console.log(decoded);
        const user = await User.findOne({ where: { id: decoded.id } });
        console.log("***************", user);
        if (!user) {
          return res.status(404).json({ error: "用户不存在" });
        }
        const { username, email } = user;
        return res.json({ username, email });
      }
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "服务器错误" });
  }
};
